package com.example.deepseek.controller;

import com.example.deepseek.model.Message;
import com.example.deepseek.service.DeepseekStreamingService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 流式聊天控制器
 * 处理流式消息发送请求
 */
@Controller
@RequestMapping("/api/stream")
@RequiredArgsConstructor
@Slf4j
public class StreamingChatController {

    private final DeepseekStreamingService streamingService;

    /**
     * 发送流式消息
     * 会立即返回成功响应，然后通过WebSocket流式传输结果
     */
    @PostMapping("/chat/{sessionId}/send")
    @ResponseBody
    public ResponseEntity<Map<String, String>> sendStreamingMessage(
            @PathVariable String sessionId,
            @RequestParam String message) {

        Map<String, String> response = new HashMap<>();

        try {
            // 异步处理流式消息
            streamingService.streamMessage(sessionId, message);

            response.put("status", "streaming");
            response.put("message", "消息已接收，正在生成回复...");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("发送流式消息时出错", e);
            response.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 停止生成
     * 用于当用户想要中断当前生成时
     */
    @PostMapping("/chat/{sessionId}/stop")
    @ResponseBody
    public ResponseEntity<Map<String, String>> stopGeneration(
            @PathVariable String sessionId) {

        Map<String, String> response = new HashMap<>();

        try {
            // 调用服务停止生成
            streamingService.stopGeneration(sessionId);

            response.put("status", "stopped");
            response.put("message", "消息生成已停止");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("停止生成时出错", e);
            response.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
}